import { toast, showLoad,hideLoad } from '@/utils/common'
/**
 * 增强版 - 选择图片并上传（带详细进度提示）
 */
export const chooseAndUploadImage = (options = {}) => {
	const config = {
		count: 1,
		sizeType: ['original', 'compressed'],
		sourceType: ['album', 'camera'],
		uploadUrl: 'https://www.daolangtongge.com/read-book-api/common/upload',
		fileKey: 'file',
		showLoad: true,
		chooseText: '选择图片中...',
		uploadText: '上传中',
		showProgress: true,
		...options
	};

	return new Promise((resolve, reject) => {
		if (config.showLoad) {
			showLoad(config.chooseText);
		}

		uni.chooseImage({
			count: config.count,
			sizeType: config.sizeType,
			sourceType: config.sourceType,
			success: async (chooseRes) => {
				const tempFilePaths = chooseRes.tempFilePaths;
				const tempFiles = chooseRes.tempFiles; // 获取文件信息

				if (!tempFilePaths.length) {
					hideLoad();
					return reject(new Error('未选择图片'));
				}

				let completedCount = 0;
				const totalCount = tempFilePaths.length;
				const uploadResults = new Array(totalCount);
				const totalSize = tempFiles.reduce((sum, file) => sum + file.size, 0);

				// 上传所有图片
				const uploadPromises = tempFilePaths.map((filePath, index) => {
					return new Promise((upResolve, upReject) => {
						const uploadTask = uni.uploadFile({
							url: config.uploadUrl,
							filePath,
							name: config.fileKey,
							header: {
								'Content-Type': 'multipart/form-data',
								Authorization: uni.getStorageSync(
									'App-Token')
							},
							success: (uploadRes) => {
								completedCount++;
								if (uploadRes.statusCode !== 200) {
									return upReject(new Error(
										`上传失败：HTTP ${uploadRes.statusCode}`
										));
								}

								try {
									const data = JSON.parse(
										uploadRes.data);
									if (data.code === 200 && data
										.url) {
										uploadResults[index] = data
											.url;
										upResolve(data.url);
									} else {
										upReject(new Error(data
											.msg || '上传失败'));
									}
								} catch (e) {
									upReject(new Error('上传结果解析失败'));
								}
							},
							fail: (err) => {
								completedCount++;
								upReject(err);
							}
						});

						// 监听上传进度
						if (config.showProgress) {
							uploadTask.onProgressUpdate((res) => {
								let progressText = config.uploadText;

								if (totalCount > 1) {
									// 多图：显示总体进度和当前文件进度
									const overallProgress = Math.round((
										completedCount /
										totalCount) * 100);
									progressText =
										`${config.uploadText} ${completedCount}/${totalCount} (${overallProgress}%)`;
									if (res.progress < 100) {
										progressText +=
											` - 当前文件: ${res.progress}%`;
									}
								} else {
									// 单图：显示详细进度
									progressText =
										`${config.uploadText} (${res.progress}%)`;
									if (res.totalBytesExpectedToSend >
										0) {
										const sentMB = (res
											.totalBytesSent / 1024 /
											1024).toFixed(1);
										const totalMB = (res
											.totalBytesExpectedToSend /
											1024 / 1024).toFixed(1);
										progressText +=
											` ${sentMB}/${totalMB}MB`;
									}
								}

								showLoad(progressText);
							});
						}
					});
				});

				// 处理上传结果
				Promise.all(uploadPromises)
					.then((urls) => {
						hideLoad();
						toast('上传成功');
						resolve(config.count === 1 ? urls[0] : urls);
					})
					.catch((err) => {
						hideLoad();
						toast(err.message || '上传失败');
						reject(err);
					});
			},
			fail: (err) => {
				hideLoad();
				toast('选择图片失败');
				reject(err);
			}
		});
	});
};